﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using ProjectStudy.App_Code;
namespace ProjectStudy.Ajax
{
    /// <summary>
    /// Menu_Manage 的摘要说明
    /// </summary>
    public class Menu_Manage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action=context.Request["action"];
            string result="";
            switch (action)
            {
                case "MenuSearch": result= MenuSearch(context);
                    break;
                case "MenuAdd": result= MenuAdd(context);
                    break;
                case "MenuModify": result = MenuModify(context);
                    break;
                case "MenuDel": result = MenuDel(context);
                    break;
                case "GetGroup": result = GetGroup(context);
                    break;
                case "GetMenuList": result = GetMenuList(context);
                    break;
                case "GetGroupList": result = GetGroupList(context);
                    break;
            }
            context.Response.Write(result);

        }

        private string MenuModify(HttpContext context)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string menuid=context.Request["menuid"];            
            string fatherid=context.Request["fatherid"];
            string secondid=context.Request["secondid"];
            string menuname=context.Request["menuname"];
            string url=context.Request["url"];
            string pageid=context.Request["pageid"];
            string group=context.Request["group"];
            string modifyby=SysSession.UserName;
            string modifytime= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string sql = "update Menu set fatherId=@fatherid,menuName=@menuname,url=@url,pageId=@pageid,userGroup=@group,modifyBy=@modifyby,modifyTime=@modifytime where menuId=@menuid";
            if(fatherid=="-1")
            {
              fatherid="0";
            }
            else
            {
              if(secondid!="-1")
              {
                fatherid=secondid;
              }
            }
            SqlParameter[] ps = { 
                                new SqlParameter("@fatherid",fatherid),
                                new SqlParameter("@menuname",menuname),
                                new SqlParameter("@url",url),
                                new SqlParameter("@pageid",pageid),
                                new SqlParameter("@group",group),
                                new SqlParameter("@modifyby",modifyby),
                                new SqlParameter("@modifytime",modifytime),
                                new SqlParameter("@menuid",menuid),
                                };
            int a = DBAccess.ExecuteNonQuery(sql,ps);
            if (a > 0)
            {
                dic.Add("status","success");
            }
            else
            {
                dic.Add("status","updateErr");
            }
            return JsonConvert.SerializeObject(dic);

        }

        private string MenuDel(HttpContext context)
        {
            string menuIds = context.Request["menuId"];
            menuIds = menuIds.Replace("[", "").Replace("]", "").Replace("\"", "");
            string[] s1= menuIds.Split(',');

            string[] pageid = context.Request["pageid"].Replace("[", "").Replace("]", "").Replace("\"", "").Split(',');

            Dictionary<string, string> dic = new Dictionary<string, string>();
            string err = "菜单Id为";
            for (int i = 0; i < s1.Length; i++)
            {
                string sql = "delete from Menu where menuId=@menuId";
                SqlParameter ps = new SqlParameter("@menuId",s1[i]);
                int a=DBAccess.ExecuteNonQuery(sql, ps);
                if (a <= 0)
                {
                    menuIds = menuIds + " " + s1[i];
                }
            }

            if (pageid.Length > 0)
            {
                for (int i = 0; i < pageid.Length; i++)
                {
                    string sql2 = "delete from PageACL where PageId=@pageid";
                    SqlParameter ps2 = new SqlParameter("@pageid", pageid[i]);
                    DBAccess.ExecuteNonQuery(sql2, ps2);
                }
            }

            if (err != "菜单Id为")
            {
                menuIds = menuIds + "的菜单删除失败！";
                dic.Add("status", "delErr");
                dic.Add("errDetail", err);
            }
            else
            {
                dic.Add("status","success");
            }
            return JsonConvert.SerializeObject(dic);
                
        }

        private string MenuAdd(HttpContext context)
        {
            string fatherId=context.Request["fatherId"];
            string SecondMenuId = context.Request["SecondMenuId"];
            string menuName = context.Request["menuName"];
            string url=context.Request["url"];
            string group = context.Request["group"];
            string menuId = Guid.NewGuid().ToString();
            string pageId = context.Request["PageId"].ConvertObjToStr();
            string rightClass = SysSession.classRight.ConvertObjToStr();
            string username = SysSession.UserName.ConvertObjToStr();
            DataTable dt = new DataTable();
            string sql = "";
            Dictionary<string,string> dic = new Dictionary<string,string>();
            sql = "select 1 from Menu where pageId=@pageid";
            SqlParameter ps1 = new SqlParameter("@pageid",pageId);
            dt = DBAccess.ExecuteDataTable(sql, ps1);
            if (dt.Rows.Count > 0)
            {
                dic.Add("status", "dataduplicate");
            }
            else
            {
                if (fatherId == "-1")
                {
                    fatherId = "0";
                }
                else
                {
                    if (SecondMenuId != "-1")
                    {
                        fatherId = SecondMenuId;
                    }
                    
                }
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sql = "insert into Menu(menuId,fatherId,menuName,url,pageId,userGroup,createBy,createTime) values(@menuId,@fatherId,@menuName,@url,@pageid,@userGroup,@createBy,@createTime)";
                SqlParameter[] ps2 = { 
                                     new SqlParameter("@menuId",menuId),
                                     new SqlParameter("@fatherId",fatherId),
                                     new SqlParameter("@menuName",menuName),
                                     new SqlParameter("@url",url),
                                     new SqlParameter("@pageid",pageId),
                                     new SqlParameter("@userGroup",group),
                                     new SqlParameter("@createBy",username),
                                     new SqlParameter("@createTime",time)
                                     };

                    int a = DBAccess.ExecuteNonQuery(sql, ps2);
                    if (pageId != "")
                    {
                        sql = "insert into PageACL(PageId,PageURL,PageUserGroup,PageRightClass) values(@pageid,@url,@group,@class)";
                        SqlParameter[] ps3 = { 
                                     new SqlParameter("@pageid",pageId),
                                     new SqlParameter("@url",url),
                                     new SqlParameter("@group",group),
                                     new SqlParameter("@class",rightClass)
                                     };
                        int b = DBAccess.ExecuteNonQuery(sql, ps3);

                        if (a <= 0 || b <= 0)
                        {
                            //dbr.Rollback();
                            dic.Add("status", "updateErr");
                        }
                        else
                        {
                            dic.Add("status", "success");
                        }
                    }
                    else
                    {
                        if (a > 0)
                        {
                            dic.Add("status", "success");
                        }
                        else
                        {
                            dic.Add("status", "updateErr");
                        }
                    }
            }
            return JsonConvert.SerializeObject(dic);
        }

        private string GetGroupList(HttpContext context)
        {
            string sql = "select GroupName,class from GroupClass";
            DataTable dt = DBAccess.ExecuteDataTable(sql);
            return JsonConvert.SerializeObject(dt);
        }

        private string GetMenuList(HttpContext context)
        {
            string menuClass = context.Request["menuClass"];
            string sql ="";
            string group = context.Request["group"];
            DataTable dt = new DataTable();
            
            if (menuClass == "1")
            {
                sql = "select menuId,menuName from Menu where fatherId=0 and userGroup=@group";
                
                SqlParameter ps1=new SqlParameter("@group",group);
                dt = DBAccess.ExecuteDataTable(sql,ps1);
            }
            else if (menuClass == "2")
            {
                sql = "select menuId,menuName from Menu where fatherId=@fatherId and userGroup=@group";
                string fatherId = context.Request["fatherId"];
                SqlParameter[] ps2 ={
                      new SqlParameter("@fatherId", fatherId),
                     new SqlParameter("@group", group)
                };
                dt = DBAccess.ExecuteDataTable(sql,ps2);
            }
            return JsonConvert.SerializeObject(dt);
        }

        private string GetGroup(HttpContext context)
        {
            string sql = "select GroupName,class from GroupClass";
            DataTable dt = DBAccess.ExecuteDataTable(sql);
            return JsonConvert.SerializeObject(dt);
        }

        private string MenuSearch(HttpContext context)
        {
            string requirement=context.Request["requirement"];
            string sql = "";
            DataTable dt = new DataTable();
            if (requirement == "all")
            {
                sql = "select * from Menu";
                dt = DBAccess.ExecuteDataTable(sql);
            }
            else
            {
                sql = "select * from Menu where userGroup=@group";
                SqlParameter ps = new SqlParameter("@group", requirement);
                dt = DBAccess.ExecuteDataTable(sql, ps);
            }
            return JsonConvert.SerializeObject(dt);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}